package com.cta.view.imports.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;

import com.cta.entity.Contact;
import com.cta.view.imports.AbstractReader;
import com.cta.view.imports.Reader;

public class ExcelReader extends AbstractReader<Contact> {

	@Override
	public List<String> getExtension() {
		List<String> extension = new ArrayList<String>(3);
		extension.add("xls");
		return extension;
	}

	@Override
	public List<Contact> getData(InputStream is) throws Exception {
		List<Contact> data = new ArrayList<Contact>();
		HSSFWorkbook workBook = new HSSFWorkbook(is);
		HSSFSheet sheet = workBook.getSheetAt(0);
		Iterator<Row> rows = sheet.rowIterator();
		while (rows.hasNext()) {
			Row row = rows.next();
			System.out.println("Row No.: " + row.getRowNum());
			Iterator<Cell> cells = row.cellIterator();
			while (cells.hasNext()) {
				Cell cell = cells.next();

				System.out.println("Cell No.: " + cell.getColumnIndex());
				switch (cell.getCellType()) {
				case HSSFCell.CELL_TYPE_NUMERIC: {

					// cell type numeric.
					System.out.println("Numeric value: " + cell.getNumericCellValue());

					break;
				}

				case HSSFCell.CELL_TYPE_STRING: {

					// cell type string.
					RichTextString richTextString = cell.getRichStringCellValue();

					System.out.println("String value: " + richTextString.getString());

					break;
				}

				default: {

					// types other than String and Numeric.
					System.out.println("Type not supported.");

					break;
				}
				}
			}
		}
		return data;
	}
	
	public static List<Contact> getEndResults(InputStream is, String fileName) throws Exception{
		Reader<Contact> rd = new ExcelReader();
		return rd.getResults(is, fileName);
	}

}
